//
//  HomeView.m
//  违章查询助手
//
//  Created by qianfeng on 15/10/24.
//  Copyright (c) 2015年 LY. All rights reserved.
//

#import "HomeView.h"
#import "twohome.h"
#import "Threehome.h"
#import "Homehead.h"
#import "LiycRequest.h"
#import "CarLife.h"
#import "BreakRulesVC.h"
#import "CarInsurance.h"
#import "CarPrice.h"
#import "AddCarVC.h"
#import "LivingRoad.h"
#import "PopupListComponent.h"
#import "AddDriveVC.h"

NSNumber * cityId;

@interface HomeView ()<UITableViewDelegate,UITableViewDataSource,CityVCDelegate,PopupListComponentDelegate>

@property(nonatomic,strong)PopupListComponent * activePopup;
@end

@implementation HomeView
{
    UITableView * _tabView;
    NSArray * array;
    NSMutableData * _data;
    Wether * _model;
    Homehead * headView;

}
@synthesize activePopup = _activePopup;


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"违章查询";
    self.automaticallyAdjustsScrollViewInsets=NO;
    self.view.backgroundColor=[UIColor whiteColor];
    [self CreateData];
    [self creatNav];
    [self creatNavBar];
    [self creatTabView];

  }

-(void)CreateData
{
    [LiycRequest getWetherWithBlock:^(id obj, NSError *error) {
        if (!error) {
            NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:obj options:NSJSONReadingMutableContainers error:nil];
            NSDictionary * dic1 = dic[@"result"];
            array = dic1[@"items"];
            [self creatHeadView];
        }
    }];

}

-(void)creatTabView
{
    _tabView=[[UITableView alloc]initWithFrame:CGRectMake(0, 64, self.view.bounds.size.width, self.view.bounds.size.height-64) style:UITableViewStyleGrouped];
    _tabView.delegate=self;
    _tabView.dataSource=self;
    _tabView.showsVerticalScrollIndicator = NO;
    _tabView.separatorStyle=UITableViewCellSeparatorStyleNone;
    
    [self.view addSubview:_tabView];
    [_tabView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(0);
        make.top.equalTo(self.view.mas_top).offset(64);
        make.right.equalTo(self.view.mas_right).offset(0);
        make.bottom.equalTo(self.view.mas_bottom).offset(0);
    }];
    
    
    [self creatHeadView];
    
}

-(void)creatHeadView
{
    UIView * view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, _tabView.bounds.size.width, 200) ];
    view.backgroundColor=[UIColor whiteColor];
    [_tabView addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_tabView.mas_left).offset(0);
        make.right.equalTo(_tabView.mas_right).offset(0);
        make.top.equalTo(_tabView.mas_top).offset(0);
        make.height.equalTo(@200);
    }];

    
    _model = [[Wether alloc]initWithDict:array[0]];
    

    UIImageView * imageview=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, _tabView.bounds.size.width, 200)];
    if ([_model.weathertext isEqualToString:@"晴"]) {
        
        imageview.image=[UIImage imageNamed:@"u=3170785536,3567864918&fm=21&gp=0"];
    
    }else if ([_model.weathertext isEqualToString:@"雨"] || [_model.weathertext isEqualToString:@"阴雨转阴"] ||[_model.weathertext isEqualToString:@"小雨"])
    {
         imageview.image=[UIImage imageNamed:@"20140111145554_vWarP"];
    
    }else if ([_model.weathertext isEqualToString:@"风"])
    {
        imageview.image=[UIImage imageNamed:@"u=4081805926,859989165&fm=21&gp=0"];
    }else if ([_model.weathertext isEqualToString:@"阴"])
    {
         imageview.image=[UIImage imageNamed:@"u=146320311,198457844&fm=21&gp=0"];
    
    }else if ([_model.weathertext isEqualToString:@"晴间多云"] || [_model.weathertext isEqualToString:@"晴转多云间晴"])
    {
        imageview.image=[UIImage imageNamed:@"u=2774951494,3278127734&fm=21&gp=0"];
    }
    
    else
    {
        imageview.image=[UIImage imageNamed:@"u=189274407,3158103747&fm=21&gp=0"];
    
    }
    
       [view addSubview:imageview];
   
    headView=[[[NSBundle mainBundle] loadNibNamed:@"Homehead" owner:nil options:nil] lastObject];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_tabView.mas_left).offset(0);
        make.right.equalTo(_tabView.mas_right).offset(0);
        make.top.equalTo(_tabView.mas_top).offset(0);
        make.height.equalTo(@200);
    }];
    
    if (array == nil) {
        
    }else{

               headView.washcar.text = _model.xiche;
        headView.temputure.text = [NSString stringWithFormat:@"%@C~%@C",_model.lowtemperature,_model.hightemperature];
        headView.time.text = _model.date;
        headView.weather.text = [NSString stringWithFormat:@"| %@",_model.weathertext];
        if (_city.length == 0) {
            headView.cityName.text = @"北京";
        }else{
            headView.cityName.text = _city;
        }
        headView.air.text=[NSString stringWithFormat:@"%@ %@",_model.air,_model.airtext];
    }
    
   [headView.cityBtn addTarget:self action:@selector(twoBtn) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:headView];
    _tabView.tableHeaderView=view;
}

#pragma mark----UITableViewDelegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 0;

}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return nil;

}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        return 200;
        
    }else if (section==2)
    {
        return 100;

    }
    return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section==1) {
        UIView * view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, _tabView.bounds.size.width, 200) ];
        view.backgroundColor=[UIColor whiteColor];
        
        NSArray * nameArr=@[@"违章高发地",@"实时路况",@"加油充值",@"低价车险",@"汽车报价",@"行车生活"];
        NSArray * imageArr=@[@"ic_li_menu_pm_bad.png",@"ic_li_menu_traffic.png",@"ic_near_jiayouzhan.png",@"identifity_icon_v.png",@"ic_wzprice.png",@"ic_nearby.png"];
        
        for (int i=0; i<nameArr.count; i++) {
            
            twohome * headView1=[[[NSBundle mainBundle] loadNibNamed:@"twohome" owner:nil options:nil] lastObject];
            
            headView1.frame=CGRectMake((i%3)*(_tabView.bounds.size.width/3), i/3*100, (_tabView.bounds.size.width/3), 100);

            headView1.Image.image=[UIImage imageNamed:imageArr[i]];
            headView1.active.text=nameArr[i];
            headView1.Btn.tag=10+i;
            [headView1.Btn addTarget:self action:@selector(TwoBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            [view addSubview:headView1];
        }
        return view;
        
    }else if(section==2)
    {
        UIView * view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, _tabView.bounds.size.width, 100) ];
        view.backgroundColor=[UIColor whiteColor];
        
        Threehome * headView2=[[[NSBundle mainBundle] loadNibNamed:@"Threehome" owner:nil options:nil] lastObject];
        
      
        [headView2.Btn addTarget:self action:@selector(ThreeBtn) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:headView2];
        [headView2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(view.mas_left).offset(0);
            make.right.equalTo(view.mas_right).offset(0);
            make.top.equalTo(view.mas_top).offset(0);
            make.height.equalTo(@100);
        }];

        return view;
    }

    return nil;
}

#pragma mark-----Button

-(void)twoBtn
{
    CityVC * city=[[CityVC alloc]init];
    
     UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:city];
    city.delegate=self;
    cityId = _cid;
    [self presentViewController:nav animated:YES completion:nil];
    
}

//代理传值获取城市名
-(void)sendString:(NSString *)string andId:(NSNumber *)cid
{
    _city=string;
    _cid=cid;
    cityId = cid;
    [self CreateData];
    
    [_tabView reloadData];
}

-(void)TwoBtnClick:(UIButton *)btn
{
    switch (btn.tag) {
        case 10:
        {
            BreakRulesVC * vc = [[BreakRulesVC alloc]init];

            [self.navigationController pushViewController:vc animated:YES];
        }
            
            break;
        case 11:
        {
            LivingRoad * road = [[LivingRoad alloc]init];
            [self.navigationController pushViewController:road animated:YES];
        }
            break;
        case 12:
        {
            UIAlertView * view=[[UIAlertView alloc]initWithTitle:@"抱歉" message:@"此功能还未开放" delegate: self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [view show];
            
        }
            
            break;
        case 13:
        {
            CarInsurance * insurance=[[CarInsurance alloc]init];
            UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:insurance];
            [self presentViewController:nav animated:YES completion:nil];
            
        }
            
            break;
        case 14:
        {
            CarPrice * price=[[CarPrice alloc]init];
            UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:price];
            [self presentViewController:nav animated:YES completion:nil];
            
        }
            
            break;
        case 15:
        {
            CarLife * carlife=[[CarLife alloc]init];
            cityId = _cid;
            UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:carlife];
            [self presentViewController:nav animated:YES completion:nil];
        }
            
            break;
        default:
            break;
    }

}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self creatNav];
    [self creatNavBar];
}

-(void)ThreeBtn
{
        AddCarVC * addCar=[[AddCarVC alloc]init];
        UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:addCar];
        [self presentViewController:nav animated:YES completion:nil];
}
#pragma mark-------creatNavigation
-(void)creatNav
{
    UINavigationBar * bar=self.navigationController.navigationBar;
    [bar setBackgroundImage:[UIImage imageNamed:@"custom_dialog_btn_bg"] forBarMetrics:UIBarMetricsDefault];
    [self.view addSubview:bar];
    
}

-(void)creatNavBar
{
    
    UIButton * left=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 35, 35)];
    
    [left setBackgroundImage:[UIImage imageNamed:@"btn_more"] forState:UIControlStateNormal];
    UIButton * right=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 35, 35)];
    [right setBackgroundImage:[UIImage imageNamed:@"btn_add"] forState:UIControlStateNormal];
    [right addTarget:self action:@selector(rightBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * leftItem=[[UIBarButtonItem alloc]initWithCustomView:left];
    UIBarButtonItem * rightItem=[[UIBarButtonItem alloc]initWithCustomView:right];
    self.navigationItem.leftBarButtonItem=leftItem;
    self.navigationItem.rightBarButtonItem=rightItem;
}

-(void)rightBtn:(UIButton *)btn
{
    if (self.activePopup) {
        
        [self.activePopup hide];
    }

    PopupListComponent *popupList = [[PopupListComponent alloc] init];
    NSArray* listItems = nil;
    listItems = [NSArray arrayWithObjects:
                 [[PopupListComponentItem alloc] initWithCaption:@"添加车辆" image:[UIImage imageNamed:@"btn_map_enlarge"]
                                                          itemId:1 showCaption:YES],
                 [[PopupListComponentItem alloc] initWithCaption:@"添驾照"  image:[UIImage imageNamed:@"btn_map_enlarge"]
                                                          itemId:2 showCaption:YES],
                 [[PopupListComponentItem alloc] initWithCaption:@"刷新"  image:[UIImage imageNamed:@"road_fresh_s"]
                                                          itemId:3 showCaption:YES],
                 nil];
    
   
    popupList.imagePaddingHorizontal = 5;
    popupList.imagePaddingVertical = 2;
    popupList.textPaddingHorizontal = 5;
    popupList.alignment = UIControlContentHorizontalAlignmentLeft;
    [popupList useSystemDefaultFontNonBold];
    popupList.userInfo = @"Value to hold on to";
    
    [popupList showAnchoredTo:btn inView:self.view withItems:listItems withDelegate:self];
    
    self.activePopup = popupList;


}

#pragma mark - Delegate Callbacks


- (void) popupListcomponent:(PopupListComponent *)sender choseItemWithId:(int)itemId
{
    NSLog(@"User chose item with id = %d", itemId);
    switch (itemId) {
        case 1:
        {
        
            AddCarVC * car=[[AddCarVC alloc]init];
            UINavigationController * nav=[[UINavigationController alloc]initWithRootViewController:car];
            [self presentViewController:nav animated:YES completion:nil];
        }
            break;
        case 2:
        {
            AddDriveVC* drive=[[AddDriveVC alloc]init];
            UINavigationController * nav=[[UINavigationController alloc]initWithRootViewController:drive];
            [self presentViewController:nav animated:YES completion:nil];
        }
            break;
        case 3:
        {
            [_tabView reloadData];
           
        }
            break;
        default:
            break;
    }
    self.activePopup = nil;
}

- (void) popupListcompoentDidCancel:(PopupListComponent *)sender
{
    NSLog(@"Popup cancelled");
    self.activePopup = nil;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
